document.addEventListener('DOMContentLoaded', function() {
    // 设置页面导航切换
    const settingsNavItems = document.querySelectorAll('.settings-nav-item');
    const settingsSections = document.querySelectorAll('.settings-section');
    const settingsContent = document.querySelector('.settings-content');
    const scrollIndicator = document.querySelector('.scroll-indicator');
    settingsNavItems.forEach(item => {
        item.addEventListener('click', function() {
            // 更新导航项状态
            settingsNavItems.forEach(navItem => navItem.classList.remove('active'));
            this.classList.add('active');
            // 更新内容区域
            const targetSection = this.getAttribute('data-settings');
            settingsSections.forEach(section => section.classList.remove('active'));
            document.getElementById(`${targetSection}-settings`).classList.add('active');
            // 内容区域滚动到顶部
            if (settingsContent) {
                settingsContent.scrollTop = 0;
            }
            
            // 如果点击的是医生设置项，根据角色加载不同内容
            if (targetSection === 'doctor') {
                const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
                if (userData.role === 'PATIENT') {
                    // 患者角色：加载医生绑定请求和当前医生信息
                    loadPatientDoctorBindingRequests();
                    loadPatientCurrentDoctor();
                } else if (userData.role === 'DOCTOR') {
                    // 医生角色：加载医生专业资料
                    loadDoctorProfile();
                }
            }
        });
    });
    
    // 加载用户个人资料数据
    loadUserProfileData();
    
    // 头像上传预览
    const avatarUpload = document.getElementById('avatar-upload');
    if (avatarUpload) {
        avatarUpload.addEventListener('change', function(event) {
            const file = event.target.files[0];
            if (file) {
                // 预览文件
                const reader = new FileReader();
                reader.onload = function(e) {
                    const avatarPreview = document.querySelector('.avatar-preview img');
                    if (avatarPreview) {
                        avatarPreview.src = e.target.result;
                    }
                };
                reader.readAsDataURL(file);
                
                // 上传文件
                uploadAvatar(file);
            }
        });
    }
    
    // 设置用户名输入框为只读
    const usernameInput = document.querySelector('#profile-settings input[type="text"]');
    if (usernameInput) {
        usernameInput.readOnly = true;
        usernameInput.classList.add('read-only');
    }
    
    // 上传头像到服务器
    function uploadAvatar(file) {
        // 显示上传中提示
        showNotification('头像上传中...', 'info');
        
        // 显示上传状态
        const avatarPreview = document.querySelector('.avatar-preview');
        if (avatarPreview) {
            avatarPreview.classList.add('uploading');
        }
        
        const formData = new FormData();
        formData.append('file', file);
        
        fetch('/api/files/upload/avatar', {
            method: 'POST',
            body: formData,
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('上传失败');
            }
            return response.json();
        })
        .then(data => {
            // 移除上传状态
            if (avatarPreview) {
                avatarPreview.classList.remove('uploading');
            }
            
            // 更新用户头像URL
            updateUserAvatar(data.url);
        })
        .catch(error => {
            console.error('Error:', error);
            // 移除上传状态
            if (avatarPreview) {
                avatarPreview.classList.remove('uploading');
            }
            showNotification('头像上传失败，请重试', 'error');
        });
    }
    
    // 更新用户头像
    function updateUserAvatar(avatarUrl) {
        // 从会话存储中获取当前用户ID
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        const userId = userData.id;
        
        if (!userId) {
            showNotification('无法获取用户信息，请重新登录', 'error');
            return;
        }
        
        fetch(`/api/users/${userId}/avatar`, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ avatarUrl: avatarUrl }),
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('更新头像失败');
            }
            return response.json();
        })
        .then(data => {
            // 更新成功
            showNotification('头像更新成功', 'success');
            
            // 更新会话存储中的用户数据
            userData.avatarUrl = avatarUrl;
            sessionStorage.setItem('user', JSON.stringify(userData));
            
            // 更新页面上所有的用户头像
            document.querySelectorAll('.avatar').forEach(avatar => {
                avatar.src = avatarUrl;
            });
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('头像信息更新失败，请重试', 'error');
        });
    }
    
    // 添加医生按钮点击事件
    const addDoctorBtn = document.getElementById('add-doctor-btn');
    if (addDoctorBtn) {
        addDoctorBtn.addEventListener('click', function() {
            // 获取添加医生的表单/区域，并将其滚动到可见区域
            const addDoctorSection = document.querySelector('.setting-card:last-child');
            if (addDoctorSection) {
                const offsetTop = addDoctorSection.offsetTop;
                settingsContent.scrollTop = offsetTop - 50; // 留出一些顶部空间
            }
        });
    }
    
    // 设置页面表单提交
    const saveButtons = document.querySelectorAll('.settings-form .btn-primary');
    saveButtons.forEach(button => {
        button.addEventListener('click', function(event) {
            event.preventDefault();
            
            // 获取当前表单的数据
            const form = this.closest('.settings-form');
            if (!form) return;
            
            // 确定表单类型并调用相应的处理函数
            if (form.closest('#profile-settings')) {
                saveProfileInfo(form);
            } else if (form.closest('#health-settings')) {
                saveHealthInfo(form);
            } else if (form.closest('#security-settings')) {
                // 可能有多个表单，需要检查具体是哪一个
                const passwordForm = form.closest('.setting-card');
                if (passwordForm && passwordForm.querySelector('h3').textContent.includes('修改密码')) {
                    changePassword(form);
                }
            } else if (form.closest('#privacy-settings')) {
                savePrivacySettings(form);
            } else if (form.closest('#notifications-settings')) {
                saveNotificationSettings(form);
            } else if (form.closest('#doctor-settings')) {
                saveDoctorSettings(form);
            }
        });
    });
    
    // 加载用户个人资料数据
    function loadUserProfileData() {
        // 从会话存储中获取当前用户ID
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        const userId = userData.id;
        
        if (!userId) {
            showNotification('无法获取用户信息，请重新登录', 'error');
            return;
        }
        
        // 从API获取最新的用户数据
        fetch(`/api/users/${userId}`, {
            method: 'GET',
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('获取用户信息失败');
            }
            return response.json();
        })
        .then(user => {
            // 更新用户数据到会话存储
            sessionStorage.setItem('user', JSON.stringify(user));
            
            // 填充个人资料表单
            populateProfileForm(user);
            
            // 根据用户角色调整导航项
            adjustSettingsByUserRole(user.role);
            
            // 如果是患者角色，加载患者健康信息
            if (user.role === 'PATIENT') {
                loadPatientData(userId);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            // 如果API调用失败，尝试使用会话存储中的数据
            if (userData.username) {
                populateProfileForm(userData);
                adjustSettingsByUserRole(userData.role);
                
                // 如果是患者角色，尝试加载患者健康信息
                if (userData.role === 'PATIENT') {
                    loadPatientData(userId);
                }
            } else {
                showNotification('无法加载用户资料，请重新登录', 'error');
            }
        });
    }
    
    // 加载患者健康信息
    function loadPatientData(userId) {
        fetch(`/api/patients/${userId}`, {
            method: 'GET',
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                // 如果是404，可能是患者记录尚未创建，这是可以接受的
                if (response.status === 404) {
                    console.log('Patient record not found, may need to be created');
                    return null;
                }
                throw new Error('获取患者健康信息失败');
            }
            return response.json();
        })
        .then(patientData => {
            if (patientData) {
                populateHealthForm(patientData);
            }
        })
        .catch(error => {
            console.error('Error loading patient data:', error);
            showNotification('加载健康信息失败，请稍后重试', 'error');
        });
    }
    
    // 填充健康信息表单
    function populateHealthForm(patientData) {
        // 获取表单元素
        const heightInput = document.getElementById('patient-height');
        const weightInput = document.getElementById('patient-weight');
        const bloodTypeSelect = document.getElementById('patient-blood-type');
        const allergiesTextarea = document.getElementById('patient-allergies');
        const medicalHistoryTextarea = document.getElementById('patient-medical-history');
        const emergencyContactInput = document.getElementById('patient-emergency-contact');
        const emergencyPhoneInput = document.getElementById('patient-emergency-phone');
        
        // 设置表单值
        if (heightInput && patientData.height) {
            heightInput.value = patientData.height;
        }
        
        if (weightInput && patientData.weight) {
            weightInput.value = patientData.weight;
        }
        
        if (bloodTypeSelect && patientData.bloodType) {
            const option = bloodTypeSelect.querySelector(`option[value="${patientData.bloodType}"]`);
            if (option) {
                option.selected = true;
            }
        }
        
        if (allergiesTextarea && patientData.allergies) {
            allergiesTextarea.value = patientData.allergies;
        }
        
        if (medicalHistoryTextarea && patientData.medicalHistory) {
            medicalHistoryTextarea.value = patientData.medicalHistory;
        }
        
        if (emergencyContactInput && patientData.emergencyContact) {
            emergencyContactInput.value = patientData.emergencyContact;
        }
        
        if (emergencyPhoneInput && patientData.emergencyPhone) {
            emergencyPhoneInput.value = patientData.emergencyPhone;
        }
    }
    
    // 保存健康信息
    function saveHealthInfo(form) {
        // 从会话存储中获取当前用户ID
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        const userId = userData.id;
        
        if (!userId) {
            showNotification('无法获取用户信息，请重新登录', 'error');
            return;
        }
        
        // 获取表单数据
        const height = parseFloat(document.getElementById('patient-height').value) || 170;
        const weight = parseFloat(document.getElementById('patient-weight').value) || 60;
        const bloodType = document.getElementById('patient-blood-type').value;
        const allergies = document.getElementById('patient-allergies').value;
        const medicalHistory = document.getElementById('patient-medical-history').value;
        const emergencyContact = document.getElementById('patient-emergency-contact').value;
        const emergencyPhone = document.getElementById('patient-emergency-phone').value;
        
        // 验证数值
        if (height <= 0 || weight <= 0) {
            showNotification('身高和体重必须为正数', 'error');
            return;
        }
        
        // 构造患者数据
        const patientData = {
            height: height,
            weight: weight,
            bloodType: bloodType,
            allergies: allergies,
            medicalHistory: medicalHistory,
            emergencyContact: emergencyContact,
            emergencyPhone: emergencyPhone
        };
        
        // 保存患者数据
        savePatientData(userId, patientData);
    }
    
    // 保存患者数据到服务器
    function savePatientData(userId, patientData) {
        // 先检查患者记录是否存在
        fetch(`/api/patients/${userId}`, {
            method: 'GET',
            credentials: 'same-origin'
        })
        .then(response => {
            // 如果返回404，表示需要创建新记录
            if (response.status === 404) {
                return createPatientRecord(userId, patientData);
            } else if (!response.ok) {
                throw new Error('获取患者信息失败');
            } else {
                // 记录存在，进行更新
                return updatePatientRecord(userId, patientData);
            }
        })
        .then(data => {
            if (data) {
                showNotification('健康信息保存成功', 'success');
            }
        })
        .catch(error => {
            console.error('Error saving patient data:', error);
            showNotification('保存健康信息失败，请稍后重试', 'error');
        });
    }
    
    // 创建新患者记录
    function createPatientRecord(userId, patientData) {
        return fetch(`/api/patients`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userId: userId,
                ...patientData
            }),
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('创建患者记录失败');
            }
            return response.json();
        });
    }
    
    // 更新现有患者记录
    function updatePatientRecord(userId, patientData) {
        return fetch(`/api/patients/${userId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(patientData),
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('更新患者记录失败');
            }
            return response.json();
        });
    }
    
    // 根据用户角色调整设置导航项
    function adjustSettingsByUserRole(role) {
        if (!role) return;
        
        // 获取健康信息和医生信息导航项
        const healthNavItem = document.querySelector('.settings-nav-item[data-settings="health"]');
        const doctorNavItem = document.querySelector('.settings-nav-item[data-settings="doctor"]');
        
        // 获取医生设置相关卡片
        const doctorBindingRequestsCard = document.getElementById('doctor-binding-requests-card');
        const currentDoctorCard = document.getElementById('current-doctor-card');
        const doctorProfileCard = document.getElementById('doctor-profile-card');
        const patientManagementCard = document.getElementById('patient-management-card');
        const patientDoctorPermissionsCard = document.getElementById('patient-doctor-permissions-card');
        
        if (role === 'DOCTOR') {
            // 医生角色：隐藏健康信息导航项
            if (healthNavItem) {
                healthNavItem.style.display = 'none';
            }
            
            // 同时隐藏健康信息内容区域
            const healthSection = document.getElementById('health-settings');
            if (healthSection) {
                healthSection.style.display = 'none';
            }
            
            // 显示医生专业资料编辑和患者管理卡片
            if (doctorProfileCard) doctorProfileCard.style.display = 'block';
            if (patientManagementCard) patientManagementCard.style.display = 'block';
            
            // 隐藏患者相关卡片
            if (doctorBindingRequestsCard) doctorBindingRequestsCard.style.display = 'none';
            if (currentDoctorCard) currentDoctorCard.style.display = 'none';
            if (patientDoctorPermissionsCard) patientDoctorPermissionsCard.style.display = 'none';
            
            // 如果当前激活的是健康信息，则切换到个人资料
            if (healthNavItem && healthNavItem.classList.contains('active')) {
                const profileNavItem = document.querySelector('.settings-nav-item[data-settings="profile"]');
                if (profileNavItem) {
                    profileNavItem.click();
                }
            }
        } else if (role === 'PATIENT') {
            // 患者角色：更改医生导航项标题
            if (doctorNavItem) {
                doctorNavItem.querySelector('span').textContent = '我的医生';
            }
            
            // 显示患者相关卡片
            if (doctorBindingRequestsCard) doctorBindingRequestsCard.style.display = 'block';
            if (currentDoctorCard) currentDoctorCard.style.display = 'block';
            if (patientDoctorPermissionsCard) patientDoctorPermissionsCard.style.display = 'block';
            
            // 隐藏医生相关卡片
            if (doctorProfileCard) doctorProfileCard.style.display = 'none';
            if (patientManagementCard) patientManagementCard.style.display = 'none';
        }
    }
    
    // 填充个人资料表单
    function populateProfileForm(user) {
        const profileForm = document.querySelector('#profile-settings .settings-form');
        if (!profileForm) return;
        
        // 设置头像
        const avatarImg = profileForm.querySelector('.avatar-preview img');
        if (avatarImg && user.avatarUrl) {
            avatarImg.src = user.avatarUrl;
        }
        
        // 设置用户名 (只读)
        const usernameInput = profileForm.querySelector('input[type="text"]');
        if (usernameInput) {
            usernameInput.value = user.username || '';
        }
        
        // 设置姓名
        const fullNameInput = profileForm.querySelector('input[value="张三"]');
        if (fullNameInput) {
            fullNameInput.value = user.fullName || '';
        }
        
        // 昵称可能未在User实体中定义，可根据实际情况处理
        
        // 设置性别
        const genderSelect = profileForm.querySelector('select');
        if (genderSelect && user.gender) {
            let genderValue = 'other';
            if (user.gender === 'MALE') genderValue = 'male';
            if (user.gender === 'FEMALE') genderValue = 'female';
            
            const genderOption = genderSelect.querySelector(`option[value="${genderValue}"]`);
            if (genderOption) {
                genderOption.selected = true;
            }
        }
        
        // 设置出生日期
        const dateOfBirthInput = profileForm.querySelector('input[type="date"]');
        if (dateOfBirthInput && user.dateOfBirth) {
            dateOfBirthInput.value = user.dateOfBirth;
        }
        
        // 设置电子邮箱
        const emailInput = profileForm.querySelector('input[type="email"]');
        if (emailInput) {
            emailInput.value = user.email || '';
        }
        
        // 设置手机号码
        const phoneInput = profileForm.querySelector('input[type="tel"]');
        if (phoneInput) {
            phoneInput.value = user.phoneNumber || '';
        }
        
        // 设置个人简介
        const bioTextarea = profileForm.querySelector('textarea');
        if (bioTextarea) {
            bioTextarea.value = user.bio || '';
        }
        
        // 更新页面上所有的用户名显示
        document.querySelectorAll('.user-name').forEach(element => {
            element.textContent = '欢迎，' + (user.fullName || user.username);
        });
        
        // 更新页面上所有的用户头像
        if (user.avatarUrl) {
            document.querySelectorAll('.avatar').forEach(avatar => {
                avatar.src = user.avatarUrl;
            });
        }
    }
    
    // 保存个人资料信息
    function saveProfileInfo(form) {
        // 从会话存储中获取当前用户ID
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        const userId = userData.id;
        
        if (!userId) {
            showNotification('无法获取用户信息，请重新登录', 'error');
            return;
        }
        
        // 收集表单数据
        const username = form.querySelector('input[type="text"]').value;
        const fullName = form.querySelector('input[value="张三"]').value || form.querySelector('.form-group:nth-child(3) input').value;
        const nickname = form.querySelector('input[value="健康达人"]') ? 
                         form.querySelector('input[value="健康达人"]').value : '';
        const genderSelect = form.querySelector('select');
        const gender = genderSelect ? genderSelect.value.toUpperCase() : '';
        const dateOfBirth = form.querySelector('input[type="date"]').value;
        const email = form.querySelector('input[type="email"]').value;
        const phoneNumber = form.querySelector('input[type="tel"]').value;
        const bio = form.querySelector('textarea').value;
        
        // 构造更新数据
        const profileData = {
            fullName: fullName,
            bio: bio,
            dateOfBirth: dateOfBirth
        };
        
        // 更新个人资料
        fetch(`/api/users/${userId}/profile`, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(profileData),
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('更新个人资料失败');
            }
            return response.json();
        })
        .then(data => {
            // 更新联系方式
            return updateContactInfo(userId, email, phoneNumber);
        })
        .then(() => {
            // 更新成功
            showNotification('个人资料更新成功', 'success');
            
            // 更新会话存储中的用户数据
            userData.fullName = fullName;
            userData.bio = bio;
            userData.email = email;
            userData.phoneNumber = phoneNumber;
            userData.dateOfBirth = dateOfBirth;
            sessionStorage.setItem('user', JSON.stringify(userData));
            
            // 更新页面上的用户名显示
            document.querySelectorAll('.user-name').forEach(element => {
                element.textContent = '欢迎，' + fullName;
            });
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('个人资料更新失败，请重试', 'error');
        });
    }
    
    // 更新联系信息
    function updateContactInfo(userId, email, phoneNumber) {
        const contactData = {
            email: email,
            phoneNumber: phoneNumber
        };
        
        return fetch(`/api/users/${userId}/contact`, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(contactData),
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('更新联系信息失败');
            }
            return response.json();
        });
    }
    
    // 修改密码
    function changePassword(form) {
        // 从会话存储中获取当前用户ID
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        const userId = userData.id;
        
        if (!userId) {
            showNotification('无法获取用户信息，请重新登录', 'error');
            return;
        }
        
        // 获取密码数据
        const currentPassword = form.querySelector('#current-password').value;
        const newPassword = form.querySelector('#new-password').value;
        const confirmPassword = form.querySelector('#confirm-password').value;
        
        // 验证所有密码字段都不为空
        if (!currentPassword || !newPassword || !confirmPassword) {
            showNotification('请填写所有密码字段', 'error');
            return;
        }
        
        // 验证新密码与确认密码是否一致
        if (newPassword !== confirmPassword) {
            showNotification('新密码与确认密码不一致', 'error');
            return;
        }
        
        // 验证密码长度
        if (newPassword.length < 6) {
            showNotification('新密码长度至少为6个字符', 'error');
            return;
        }
        
        // 显示加载状态
        const saveButton = form.querySelector('.btn-primary');
        const originalText = saveButton.textContent;
        saveButton.disabled = true;
        saveButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
        
        // 发送修改密码请求
        fetch(`/api/users/${userId}/change-password`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                currentPassword: currentPassword,
                newPassword: newPassword
            }),
            credentials: 'same-origin'
        })
        .then(response => {
            // 恢复按钮状态
            saveButton.disabled = false;
            saveButton.textContent = originalText;
            
            if (!response.ok) {
                // 处理不同的错误状态码
                if (response.status === 400) {
                    throw new Error('当前密码不正确');
                } else if (response.status === 401) {
                    throw new Error('未授权操作，请重新登录');
                } else if (response.status === 404) {
                    throw new Error('找不到用户信息，请重新登录');
                } else {
                    throw new Error('密码修改失败');
                }
            }
            return response.json();
        })
        .then(data => {
            // 清空密码输入框
            form.querySelectorAll('input[type="password"]').forEach(input => {
                input.value = '';
            });
            
            // 显示成功消息
            showNotification('密码修改成功', 'success');
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification(error.message || '密码修改失败，请检查当前密码是否正确', 'error');
        });
    }
    
    // 保存隐私设置
    function savePrivacySettings(form) {
        // 可以实现与个人资料类似的逻辑
        // 这里为简化，仅显示成功消息
        showNotification('隐私设置已成功保存', 'success');
    }
    
    // 保存通知设置
    function saveNotificationSettings(form) {
        // 可以实现与个人资料类似的逻辑
        // 这里为简化，仅显示成功消息
        showNotification('通知设置已成功保存', 'success');
    }
    
    // 保存医生设置
    function saveDoctorSettings(form) {
        // 可以实现与个人资料类似的逻辑
        // 这里为简化，仅显示成功消息
        showNotification('医生信息已成功保存', 'success');
    }
    
    // 通知消息显示函数
    function showNotification(message, type = 'info', closeAutomatically = true) {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.innerHTML = `
            <div class="notification-content">
                <i class="fas ${type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : type === 'warning' ? 'fa-exclamation-triangle' : 'fa-info-circle'}"></i>
                <span>${message}</span>
            </div>
            <button class="notification-close"><i class="fas fa-times"></i></button>
        `;
        
        // 管理堆叠的通知数量
        const existingNotifications = document.querySelectorAll('.notification');
        if (existingNotifications.length >= 4) {
            // 如果已经有4个通知，删除最早的一个
            document.body.removeChild(existingNotifications[0]);
        }
        
        // 添加到页面
        document.body.appendChild(notification);
        
        // 添加关闭按钮事件
        const closeBtn = notification.querySelector('.notification-close');
        closeBtn.addEventListener('click', function() {
            closeNotification(notification);
        });
        
        // 自动关闭
        if (closeAutomatically) {
            setTimeout(() => {
                closeNotification(notification);
            }, 3000);
        }
        
        // 显示通知
        setTimeout(() => {
            notification.classList.add('show');
        }, 10);
        
        return notification;
    }
    
    // 关闭通知函数
    function closeNotification(notification) {
        notification.classList.remove('show');
        notification.classList.add('fade-out');
        
        // 等待动画完成后删除
        setTimeout(() => {
            if (document.body.contains(notification)) {
                document.body.removeChild(notification);
            }
            
            // 重新调整其他通知的位置
            adjustNotificationsPosition();
        }, 300);
    }
    
    // 调整通知位置
    function adjustNotificationsPosition() {
        const notifications = document.querySelectorAll('.notification');
        notifications.forEach((notification, index) => {
            notification.style.top = `${20 + (index * 70)}px`;
        });
    }
    
    // 当从侧边导航栏点击设置时，确保设置页面正确初始化
    document.querySelectorAll('.nav-item').forEach(navItem => {
        navItem.addEventListener('click', function() {
            if (this.getAttribute('data-page') === 'settings') {
                // 确保默认显示第一个设置选项
                setTimeout(() => {
                    const firstSettingsNav = document.querySelector('.settings-nav-item');
                    if (firstSettingsNav && !firstSettingsNav.classList.contains('active')) {
                        firstSettingsNav.click();
                    }
                }, 100);
            }
        });
    });
    
    // 监听内容区域滚动，动态调整导航栏活跃状态和滚动指示器
    if (settingsContent) {
        settingsContent.addEventListener('scroll', function() {
            // 更新滚动指示器
            updateScrollIndicator();
        });
        
        // 初始化滚动指示器
        updateScrollIndicator();
        
        // 窗口大小改变时也更新滚动指示器
        window.addEventListener('resize', updateScrollIndicator);
    }
    
    // 更新滚动指示器高度和位置
    function updateScrollIndicator() {
        if (scrollIndicator && settingsContent) {
            const scrollPercentage = settingsContent.scrollTop / (settingsContent.scrollHeight - settingsContent.clientHeight);
            const scrollIndicatorHeight = (settingsContent.clientHeight / settingsContent.scrollHeight) * settingsContent.clientHeight;
            
            // 设置指示器高度和位置
            scrollIndicator.style.height = `${Math.max(30, scrollIndicatorHeight)}px`; // 最小高度30px
            scrollIndicator.style.top = `${(settingsContent.clientHeight - scrollIndicatorHeight) * scrollPercentage}px`;
            
            // 如果已经滚动，显示指示器
            if (scrollPercentage > 0) {
                scrollIndicator.style.opacity = '1';
            } else {
                scrollIndicator.style.opacity = '0';
            }
        }
    }
    
    // 获取用户登录设备记录
    function loadUserLoginDevices() {
        // 从会话存储中获取当前用户ID
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        const userId = userData.id;
        
        if (!userId) {
            showNotification('无法获取用户信息，请重新登录', 'error');
            return;
        }
        
        // 显示加载状态
        const devicesList = document.getElementById('login-devices-list');
        const emptyState = document.querySelector('.device-list-empty');
        
        if (!devicesList) return;
        
        devicesList.innerHTML = `
            <div class="loading-devices">
                <i class="fas fa-spinner fa-spin"></i>
                <span>正在加载设备信息...</span>
            </div>
        `;
        emptyState.style.display = 'none';
        
        // 获取当前设备信息
        const currentUserAgent = window.navigator.userAgent;
        const currentDate = new Date();
        
        // 获取上次登录信息
        fetch(`/api/login-records/user/${userId}/last`, {
            method: 'GET',
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('获取上次登录信息失败');
            }
            return response.json();
        })
        .then(data => {
            if (data.data) {
                updateLastLoginInfo(data.data);
            }
        })
        .catch(error => {
            console.error('Error fetching last login:', error);
        });
        
        // 获取登录设备列表
        Promise.all([
            // 获取最近登录记录
            fetch(`/api/login-records/user/${userId}/recent?limit=10`, {
                method: 'GET',
                credentials: 'same-origin'
            }),
            // 检查可疑活动
            fetch(`/api/login-records/user/${userId}/check-suspicious`, {
                method: 'GET',
                credentials: 'same-origin'
            })
        ])
        .then(([recentResponse, suspiciousResponse]) => {
            if (!recentResponse.ok) {
                throw new Error('获取登录记录失败');
            }
            
            return Promise.all([recentResponse.json(), suspiciousResponse.json()]);
        })
        .then(([recentData, suspiciousData]) => {
            const loginRecords = recentData.data || [];
            const hasSuspiciousActivity = suspiciousData.suspicious || false;
            
            // 更新安全状态
            updateSecurityStatus(hasSuspiciousActivity);
            
            // 更新设备计数
            const uniqueDevices = new Set();
            loginRecords.forEach(record => {
                uniqueDevices.add(record.deviceName || 
                                  (record.operatingSystem + ' ' + record.browser));
            });
            document.getElementById('devices-count').textContent = uniqueDevices.size;
            
            // 渲染设备列表
            if (loginRecords.length === 0) {
                devicesList.innerHTML = '';
                emptyState.style.display = 'block';
            } else {
                // 映射设备类型图标
                const deviceIcons = {
                    'MOBILE': 'fa-mobile-alt',
                    'TABLET': 'fa-tablet-alt',
                    'DESKTOP': 'fa-desktop',
                    'UNKNOWN': 'fa-question-circle'
                };
                
                devicesList.innerHTML = '';
                
                loginRecords.forEach(record => {
                    const isCurrentDevice = isMatchingUserAgent(currentUserAgent, record.userAgent);
                    const isSuspicious = record.location && 
                                        !record.location.includes('北京') && 
                                        !record.location.includes('成功'); // 简单判断，实际应更复杂
                    
                    const loginDate = new Date(record.loginTime);
                    const timeAgo = formatTimeAgo(loginDate);
                    
                    const deviceItem = document.createElement('div');
                    deviceItem.className = `device-item ${isCurrentDevice ? 'current' : ''} ${isSuspicious ? 'suspicious' : ''}`;
                    
                    const deviceName = record.deviceName || `${record.operatingSystem || '未知设备'} ${record.browser || ''}`;
                    
                    deviceItem.innerHTML = `
                        <div class="device-info">
                            <i class="fas ${deviceIcons[record.deviceType] || 'fa-laptop'}"></i>
                            <div class="device-details">
                                <h4>${deviceName}</h4>
                                <p>上次登录: ${timeAgo}</p>
                                <p class="location-info">
                                    <i class="fas fa-map-marker-alt"></i>
                                    ${record.location || '未知位置'}
                                </p>
                                <div class="device-meta">
                                    <span><i class="fas fa-globe"></i>${record.browser || '未知浏览器'}</span>
                                    <span><i class="fas fa-server"></i>${record.ipAddress || ''}</span>
                                </div>
                            </div>
                        </div>
                        <div class="device-action">
                            ${isCurrentDevice ? 
                              '<span class="current-device"><i class="fas fa-check-circle"></i> 当前设备</span>' : 
                              '<button class="btn-text logout-device" data-session="' + (record.sessionId || '') + '">注销</button>'}
                            <button class="toggle-details" title="查看详情">
                                <i class="fas fa-chevron-down"></i>
                            </button>
                        </div>
                        <div class="device-details-expand">
                            <div class="detail-row">
                                <span class="detail-label">登录时间:</span>
                                <span class="detail-value">${formatDateTime(loginDate)}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">设备类型:</span>
                                <span class="detail-value">${getDeviceTypeText(record.deviceType)}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">操作系统:</span>
                                <span class="detail-value">${record.operatingSystem || '未知'}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">浏览器:</span>
                                <span class="detail-value">${record.browser || '未知'}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">IP地址:</span>
                                <span class="detail-value">${record.ipAddress || '未知'}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">登录状态:</span>
                                <span class="detail-value ${record.loginStatus === 'SUCCESS' ? 'security-status-safe' : 'security-status-danger'}">
                                    ${record.loginStatus === 'SUCCESS' ? '成功' : '失败'}
                                </span>
                            </div>
                            ${record.failReason ? `
                            <div class="detail-row">
                                <span class="detail-label">失败原因:</span>
                                <span class="detail-value security-status-danger">${record.failReason}</span>
                            </div>` : ''}
                        </div>
                    `;
                    
                    devicesList.appendChild(deviceItem);
                });
                
                // 添加设备详情展开/收起功能
                document.querySelectorAll('.toggle-details').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const deviceItem = this.closest('.device-item');
                        deviceItem.classList.toggle('expanded');
                    });
                });
                
                // 添加注销设备功能
                document.querySelectorAll('.logout-device').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const sessionId = this.getAttribute('data-session');
                        if (sessionId) {
                            logoutDevice(sessionId);
                        } else {
                            showNotification('无法注销此设备，会话信息不完整', 'error');
                        }
                    });
                });
            }
        })
        .catch(error => {
            console.error('Error:', error);
            devicesList.innerHTML = `
                <div class="loading-error">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>加载设备信息失败，请稍后重试</p>
                </div>
            `;
        });
    }
    
    // 注销单个设备
    function logoutDevice(sessionId) {
        if (!sessionId) return;
        
        // 显示确认对话框
        if (!confirm('确定要注销此设备吗？')) return;
        
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        const userId = userData.id;
        
        // 发送注销请求
        fetch(`/api/sessions/${userId}/logout`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ sessionId: sessionId }),
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('注销设备失败');
            }
            return response.json();
        })
        .then(data => {
            showNotification('设备已成功注销', 'success');
            // 重新加载设备列表
            loadUserLoginDevices();
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('注销设备失败，请重试', 'error');
        });
    }
    
    // 注销所有其他设备
    function logoutAllDevices() {
        // 显示确认对话框
        if (!confirm('确定要注销所有其他设备吗？这将使其他设备的会话失效。')) return;
        
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        const userId = userData.id;
        
        // 发送注销所有设备请求
        fetch(`/api/sessions/${userId}/logout-all`, {
            method: 'POST',
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('注销所有设备失败');
            }
            return response.json();
        })
        .then(data => {
            showNotification('所有其他设备已成功注销', 'success');
            // 重新加载设备列表
            loadUserLoginDevices();
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('注销所有设备失败，请重试', 'error');
        });
    }
    
    // 更新安全状态展示
    function updateSecurityStatus(hasSuspiciousActivity) {
        const statusElement = document.getElementById('security-status');
        if (!statusElement) return;
        
        if (hasSuspiciousActivity) {
            statusElement.textContent = '存在可疑登录';
            statusElement.className = 'stat-value security-status-warning';
        } else {
            statusElement.textContent = '正常';
            statusElement.className = 'stat-value security-status-safe';
        }
    }
    
    // 更新上次登录信息
    function updateLastLoginInfo(lastLogin) {
        const lastLoginElement = document.getElementById('last-login-time');
        if (!lastLoginElement || !lastLogin) return;
        
        const loginDate = new Date(lastLogin.loginTime);
        const timeAgo = formatTimeAgo(loginDate);
        lastLoginElement.textContent = timeAgo;
    }
    
    // 时间格式化为"多久之前"
    function formatTimeAgo(date) {
        const now = new Date();
        const diffMs = now - date;
        const diffSec = Math.floor(diffMs / 1000);
        const diffMin = Math.floor(diffSec / 60);
        const diffHour = Math.floor(diffMin / 60);
        const diffDay = Math.floor(diffHour / 24);
        
        if (diffDay > 30) {
            return date.toLocaleDateString();
        } else if (diffDay > 0) {
            return `${diffDay} 天前`;
        } else if (diffHour > 0) {
            return `${diffHour} 小时前`;
        } else if (diffMin > 0) {
            return `${diffMin} 分钟前`;
        } else {
            return '刚刚';
        }
    }
    
    // 格式化日期时间
    function formatDateTime(date) {
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        });
    }
    
    // 获取设备类型文本描述
    function getDeviceTypeText(deviceType) {
        const typeMap = {
            'MOBILE': '移动设备',
            'TABLET': '平板设备',
            'DESKTOP': '桌面设备',
            'UNKNOWN': '未知设备'
        };
        return typeMap[deviceType] || '未知设备';
    }
    
    // 对比User-Agent判断是否为当前设备
    function isMatchingUserAgent(current, saved) {
        if (!saved) return false;
        
        // 完全匹配
        if (current === saved) return true;
        
        // 简单匹配，检查关键特征
        const currentLower = current.toLowerCase();
        const savedLower = saved.toLowerCase();
        
        const browserKeys = ['chrome', 'firefox', 'safari', 'edge', 'opera'];
        const osKeys = ['windows', 'mac', 'android', 'ios', 'linux'];
        
        // 检查浏览器和操作系统特征是否匹配
        let browserMatch = false;
        let osMatch = false;
        
        for (const key of browserKeys) {
            if (currentLower.includes(key) && savedLower.includes(key)) {
                browserMatch = true;
                break;
            }
        }
        
        for (const key of osKeys) {
            if (currentLower.includes(key) && savedLower.includes(key)) {
                osMatch = true;
                break;
            }
        }
        
        return browserMatch && osMatch;
    }
    
    // 页面加载时执行
    function initSecuritySettings() {
        // 加载登录设备信息
        loadUserLoginDevices();
        
        // 添加刷新设备列表按钮事件
        const refreshDevicesBtn = document.getElementById('refresh-devices');
        if (refreshDevicesBtn) {
            refreshDevicesBtn.addEventListener('click', loadUserLoginDevices);
        }
        
        // 添加注销所有设备按钮事件
        const logoutAllDevicesBtn = document.getElementById('logout-all-devices');
        if (logoutAllDevicesBtn) {
            logoutAllDevicesBtn.addEventListener('click', logoutAllDevices);
        }
        
        // 为修改密码按钮添加事件监听
        const changePasswordBtn = document.getElementById('change-password-btn');
        if (changePasswordBtn) {
            changePasswordBtn.addEventListener('click', function() {
                const form = document.querySelector('.password-form');
                if (form) {
                    changePassword(form);
                }
            });
        }
    }
    
    // 当从侧边导航栏点击设置时，确保设置页面正确初始化
    document.querySelectorAll('.nav-item').forEach(navItem => {
        navItem.addEventListener('click', function() {
            if (this.getAttribute('data-page') === 'settings') {
                // 确保默认显示第一个设置选项
                setTimeout(() => {
                    const firstSettingsNav = document.querySelector('.settings-nav-item');
                    if (firstSettingsNav && !firstSettingsNav.classList.contains('active')) {
                        firstSettingsNav.click();
                    }
                    
                    // 初始化安全设置
                    initSecuritySettings();
                }, 100);
            }
        });
    });
    
    // 当设置导航项被点击时初始化对应部分
    document.querySelectorAll('.settings-nav-item').forEach(navItem => {
        navItem.addEventListener('click', function() {
            if (this.getAttribute('data-settings') === 'security') {
                // 初始化安全设置
                initSecuritySettings();
            }
        });
    });
    
    // 页面加载完成后，如果当前是设置页面且安全设置激活，则初始化安全设置
    if (document.querySelector('#settings.page-content') && 
        document.querySelector('#security-settings.active')) {
        initSecuritySettings();
    }
    
    // 加载医生绑定请求
    function loadPatientDoctorBindingRequests() {
        // 从会话存储中获取当前用户信息
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        if (!userData.id || userData.role !== 'PATIENT') {
            return;
        }
        
        // 获取页面元素
        const requestsList = document.getElementById('binding-requests-list');
        const noPendingRequestsEl = document.getElementById('no-pending-requests');
        const pendingRequestsCountEl = document.querySelector('.pending-requests-count');
        
        if (!requestsList) return;
        
        // 显示加载状态
        requestsList.innerHTML = `
            <div class="loading-state">
                <i class="fas fa-spinner fa-spin"></i>
                <p>正在加载绑定请求...</p>
            </div>
        `;
        noPendingRequestsEl.style.display = 'none';
        
        // 显示加载中通知
        const loadingNotification = showNotification('正在加载医生绑定请求...', 'info', false);
        
        // 获取绑定请求
        fetch('/api/patient/pending-requests', {
            method: 'GET',
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('获取绑定请求失败');
            }
            return response.json();
        })
        .then(requests => {
            // 移除加载中通知
            if (loadingNotification && document.body.contains(loadingNotification)) {
                loadingNotification.classList.add('fade-out');
                setTimeout(() => {
                    if (document.body.contains(loadingNotification)) {
                        document.body.removeChild(loadingNotification);
                    }
                }, 300);
            }
            
            // 清空加载状态
            requestsList.innerHTML = '';
            
            // 更新请求数量
            pendingRequestsCountEl.textContent = requests.length;
            
            if (requests.length === 0) {
                // 没有待处理的请求
                noPendingRequestsEl.style.display = 'block';
                showNotification('您没有待处理的医生绑定请求', 'info');
                return;
            } else {
                // 有待处理请求时提示
                showNotification(`您有 ${requests.length} 个待处理的医生绑定请求`, 'info');
            }
            
            // 隐藏空状态
            noPendingRequestsEl.style.display = 'none';
            
            // 渲染请求列表
            requests.forEach(request => {
                const requestEl = document.createElement('div');
                requestEl.className = 'doctor-item';
                requestEl.innerHTML = `
                    <div class="doctor-avatar">
                        <img src="${request.doctorAvatar || '/images/default-avatar.png'}" alt="医生头像">
                    </div>
                    <div class="doctor-info">
                        <h4>${request.doctorName || '未知医生'}</h4>
                        <p>${request.doctorSpecialty || '未指定专业'} - ${request.doctorHospital || '未指定医院'}</p>
                        <p><small>申请时间: ${formatTimeAgo(new Date(request.createdAt))}</small></p>
                        ${request.doctorNote ? `<p class="doctor-note"><i class="fas fa-quote-left"></i> ${request.doctorNote} <i class="fas fa-quote-right"></i></p>` : ''}
                    </div>
                    <div class="doctor-actions binding-actions">
                        <button class="btn btn-sm btn-success accept-request" data-request-id="${request.id}">接受</button>
                        <button class="btn btn-sm btn-danger reject-request" data-request-id="${request.id}">拒绝</button>
                    </div>
                `;
                
                requestsList.appendChild(requestEl);
            });
            
            // 添加接受和拒绝按钮事件监听
            addBindingRequestButtonListeners();
        })
        .catch(error => {
            console.error('Error:', error);
            
            // 移除加载中通知
            if (loadingNotification && document.body.contains(loadingNotification)) {
                loadingNotification.classList.add('fade-out');
                setTimeout(() => {
                    if (document.body.contains(loadingNotification)) {
                        document.body.removeChild(loadingNotification);
                    }
                }, 300);
            }
            
            requestsList.innerHTML = `
                <div class="error-state">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>加载绑定请求失败，请稍后重试</p>
                </div>
            `;
            
            showNotification('加载医生绑定请求失败，请稍后重试', 'error');
        });
    }
    
    // 添加绑定请求按钮事件监听
    function addBindingRequestButtonListeners() {
        // 接受请求按钮
        document.querySelectorAll('.accept-request').forEach(button => {
            button.addEventListener('click', function() {
                const requestId = this.getAttribute('data-request-id');
                confirmDoctorBindingRequest(requestId);
            });
        });
        
        // 拒绝请求按钮
        document.querySelectorAll('.reject-request').forEach(button => {
            button.addEventListener('click', function() {
                const requestId = this.getAttribute('data-request-id');
                showRejectBindingRequestDialog(requestId);
            });
        });
    }
    
    // 显示拒绝绑定请求对话框
    function showRejectBindingRequestDialog(requestId) {
        // 创建模态对话框
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3>拒绝医生绑定请求</h3>
                    <button class="close-modal">&times;</button>
                </div>
                <div class="modal-body">
                    <p>您确定要拒绝这个医生的绑定请求吗？</p>
                    <div class="form-group">
                        <label>拒绝原因 (可选)</label>
                        <textarea id="reject-reason" class="form-control" placeholder="请输入拒绝原因，医生将收到您的反馈"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary cancel-reject">取消</button>
                    <button class="btn btn-danger confirm-reject" data-request-id="${requestId}">确认拒绝</button>
                </div>
            </div>
        `;
        
        // 添加到页面
        document.body.appendChild(modal);
        
        // 防止滚动
        document.body.style.overflow = 'hidden';
        
        // 显示模态框
        setTimeout(() => {
            modal.classList.add('show');
        }, 10);
        
        // 关闭按钮
        modal.querySelector('.close-modal').addEventListener('click', () => {
            closeModal(modal);
        });
        
        // 取消按钮
        modal.querySelector('.cancel-reject').addEventListener('click', () => {
            closeModal(modal);
        });
        
        // 点击模态框外部关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                closeModal(modal);
            }
        });
        
        // 确认拒绝按钮
        modal.querySelector('.confirm-reject').addEventListener('click', function() {
            const reason = modal.querySelector('#reject-reason').value.trim();
            rejectDoctorBindingRequest(requestId, reason);
            closeModal(modal);
        });
    }
    
    // 关闭模态框
    function closeModal(modal) {
        modal.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(modal);
            document.body.style.overflow = '';
        }, 300);
    }
    
    // 确认医生绑定请求
    function confirmDoctorBindingRequest(requestId) {
        // 显示确认中状态
        const requestButton = document.querySelector(`.accept-request[data-request-id="${requestId}"]`);
        if (requestButton) {
            const originalText = requestButton.textContent;
            requestButton.disabled = true;
            requestButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
            
            // 禁用该请求的拒绝按钮
            const rejectButton = requestButton.closest('.binding-actions').querySelector('.reject-request');
            if (rejectButton) {
                rejectButton.disabled = true;
            }
        }
        
        // 发送确认请求
        fetch(`/api/patient/confirm-request/${requestId}`, {
            method: 'POST',
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('确认请求失败');
            }
            return response.json();
        })
        .then(data => {
            // 显示成功通知
            showNotification('已成功确认医生绑定请求', 'success');
            
            // 重新加载绑定请求和当前医生信息
            loadPatientDoctorBindingRequests();
            loadPatientCurrentDoctor();
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('确认请求失败，请重试', 'error');
            
            // 恢复按钮状态
            if (requestButton) {
                requestButton.disabled = false;
                requestButton.textContent = originalText;
                
                if (rejectButton) {
                    rejectButton.disabled = false;
                }
            }
        });
    }
    
    // 拒绝医生绑定请求
    function rejectDoctorBindingRequest(requestId, reason) {
        // 发送拒绝请求
        fetch(`/api/patient/reject-request/${requestId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ reason: reason }),
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('拒绝请求失败');
            }
            return response.json();
        })
        .then(data => {
            // 显示成功通知
            showNotification('已成功拒绝医生绑定请求', 'success');
            
            // 重新加载绑定请求列表
            loadPatientDoctorBindingRequests();
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('拒绝请求失败，请重试', 'error');
        });
    }
    
    // 加载患者当前的医生信息
    function loadPatientCurrentDoctor() {
        // 从会话存储中获取当前用户信息
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        if (!userData.id || userData.role !== 'PATIENT') {
            return;
        }
        
        // 获取页面元素
        const currentDoctorEl = document.getElementById('current-doctor');
        const noCurrentDoctorEl = document.getElementById('no-current-doctor');
        
        if (!currentDoctorEl) return;
        
        // 显示加载状态
        currentDoctorEl.innerHTML = `
            <div class="loading-state">
                <i class="fas fa-spinner fa-spin"></i>
                <p>正在加载医生信息...</p>
            </div>
        `;
        noCurrentDoctorEl.style.display = 'none';
        
        // 显示加载中通知
        const loadingNotification = showNotification('正在加载您的医生信息...', 'info', false);
        
        // 获取当前医生信息
        fetch('/api/patient/doctor', {
            method: 'GET',
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('获取医生信息失败');
            }
            return response.json();
        })
        .then(data => {
            // 移除加载中通知
            if (loadingNotification && document.body.contains(loadingNotification)) {
                loadingNotification.classList.add('fade-out');
                setTimeout(() => {
                    if (document.body.contains(loadingNotification)) {
                        document.body.removeChild(loadingNotification);
                    }
                }, 300);
            }
            
            // 清空加载状态
            currentDoctorEl.innerHTML = '';
            
            // 检查是否有医生
            if (data.status === 'NO_DOCTOR') {
                // 没有绑定医生
                noCurrentDoctorEl.style.display = 'block';
                currentDoctorEl.style.display = 'none';
                showNotification('您当前没有绑定医生', 'info');
                return;
            }
            
            // 隐藏空状态
            noCurrentDoctorEl.style.display = 'none';
            currentDoctorEl.style.display = 'block';
            
            // 通知用户
            showNotification('已成功加载您的医生信息', 'success');
            
            // 计算绑定时长
            const bindingDuration = getBindingDuration(new Date(data.confirmedAt));
            
            // 使用新的专业布局渲染医生信息
            const doctorEl = document.createElement('div');
            doctorEl.className = 'doctor-item';
            doctorEl.innerHTML = `
                <div class="doctor-header">
                    <img src="${data.doctorAvatar || '/images/default-avatar.png'}" alt="医生头像" class="doctor-avatar">
                    <div class="doctor-header-info">
                        <h3 class="doctor-name">${data.doctorName || '未知医生'}</h3>
                        <p class="doctor-specialty">${data.doctorSpecialty || '未指定专业'}</p>
                        <p class="binding-time">
                            <i class="fas fa-link"></i> 绑定时间: ${formatDateTime(new Date(data.confirmedAt))} (${bindingDuration})
                        </p>
                        <div>
                            <span class="doctor-badge verified"><i class="fas fa-check-circle"></i> 已认证</span>
                            ${data.doctorTitle ? `<span class="doctor-badge specialist"><i class="fas fa-star"></i> ${data.doctorTitle}</span>` : ''}
                        </div>
                    </div>
                </div>
                
                <table class="doctor-info-table">
                    <tr>
                        <th><i class="fas fa-hospital"></i> 所属医院</th>
                        <td>${data.doctorHospital || '未指定医院'}</td>
                    </tr>
                    <tr>
                        <th><i class="fas fa-stethoscope"></i> 专业领域</th>
                        <td>${data.doctorSpecialty || '未指定专业'}</td>
                    </tr>
                    ${data.doctorTitle ? `
                    <tr>
                        <th><i class="fas fa-user-md"></i> 职称</th>
                        <td>${data.doctorTitle}</td>
                    </tr>` : ''}
                    ${data.doctorContact ? `
                    <tr>
                        <th><i class="fas fa-phone"></i> 联系方式</th>
                        <td>${data.doctorContact}</td>
                    </tr>` : ''}
                    ${data.doctorEmail ? `
                    <tr>
                        <th><i class="fas fa-envelope"></i> 邮箱</th>
                        <td>${data.doctorEmail}</td>
                    </tr>` : ''}
                    ${data.doctorNote ? `
                    <tr>
                        <th><i class="fas fa-sticky-note"></i> 备注</th>
                        <td><p class="doctor-note">${data.doctorNote}</p></td>
                    </tr>` : ''}
                </table>
                
                <div class="doctor-footer">
                    <div class="doctor-rating">
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star-half-alt"></i>
                        <span>4.5</span>
                    </div>
                    <div class="doctor-actions">
                        <button class="btn btn-sm btn-primary" title="发送消息" onclick="goToMessagesWithDoctor(${data.doctorId})">
                            <i class="fas fa-comment"></i> 发消息
                        </button>
                        <button class="btn btn-sm btn-primary" title="预约咨询" onclick="bookAppointmentWithDoctor(${data.doctorId})">
                            <i class="fas fa-calendar-alt"></i> 预约
                        </button>
                        <button class="btn btn-sm btn-outline-danger unbind-doctor" title="解除绑定" data-relationship-id="${data.id}">
                            <i class="fas fa-unlink"></i> 解除绑定
                        </button>
                    </div>
                </div>
            `;
            
            currentDoctorEl.appendChild(doctorEl);
            
            // 添加解除绑定按钮事件
            addUnbindDoctorButtonListener();
        })
        .catch(error => {
            console.error('Error:', error);
            
            // 移除加载中通知
            if (loadingNotification && document.body.contains(loadingNotification)) {
                loadingNotification.classList.add('fade-out');
                setTimeout(() => {
                    if (document.body.contains(loadingNotification)) {
                        document.body.removeChild(loadingNotification);
                    }
                }, 300);
            }
            
            // 显示错误状态
            currentDoctorEl.innerHTML = `
                <div class="error-state">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>加载医生信息失败，请稍后重试</p>
                </div>
            `;
            
            // 隐藏空状态
            noCurrentDoctorEl.style.display = 'none';
            
            // 显示错误通知
            showNotification('加载医生信息失败，请稍后重试', 'error');
        });
    }
    
    // 计算绑定时长
    function getBindingDuration(bindingDate) {
        const now = new Date();
        const diffTime = Math.abs(now - bindingDate);
        const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
        
        if (diffDays < 30) {
            return `${diffDays} 天`;
        } else if (diffDays < 365) {
            const months = Math.floor(diffDays / 30);
            return `${months} 个月`;
        } else {
            const years = Math.floor(diffDays / 365);
            const remainingMonths = Math.floor((diffDays % 365) / 30);
            return remainingMonths > 0 ? `${years} 年 ${remainingMonths} 个月` : `${years} 年`;
        }
    }
    
    // 跳转到与医生的聊天页面
    function goToMessagesWithDoctor(doctorId) {
        // 切换到消息页面并打开与该医生的聊天
        const messagesNav = document.querySelector('.nav-item[data-page="messages"]');
        if (messagesNav) {
            messagesNav.click();
            // 使用自定义事件通知消息模块打开与特定医生的聊天
            const event = new CustomEvent('openChatWithDoctor', { detail: { doctorId: doctorId } });
            document.dispatchEvent(event);
        }
    }
    
    // 预约医生
    function bookAppointmentWithDoctor(doctorId) {
        // 切换到预约页面并选择该医生
        const appointmentsNav = document.querySelector('.nav-item[data-page="appointments"]');
        if (appointmentsNav) {
            appointmentsNav.click();
            // 使用自定义事件通知预约模块选择特定医生
            const event = new CustomEvent('bookAppointmentWithDoctor', { detail: { doctorId: doctorId } });
            document.dispatchEvent(event);
        }
    }
    
    // 查看医生主页
    function viewDoctorProfile(doctorId) {
        // TODO: 实现查看医生主页功能
        showNotification('医生主页功能尚未实现', 'info');
    }
    
    // 添加解除医生绑定按钮事件
    function addUnbindDoctorButtonListener() {
        document.querySelectorAll('.unbind-doctor').forEach(button => {
            button.addEventListener('click', function() {
                const relationshipId = this.getAttribute('data-relationship-id');
                showUnbindDoctorDialog(relationshipId);
            });
        });
    }
    
    // 显示解除医生绑定对话框
    function showUnbindDoctorDialog(relationshipId) {
        // 创建模态对话框
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3>解除医生绑定</h3>
                    <button class="close-modal">&times;</button>
                </div>
                <div class="modal-body">
                    <p>您确定要解除与当前医生的绑定关系吗？</p>
                    <p class="text-danger">注意：解除绑定后，医生将无法查看您的健康记录并为您提供服务。</p>
                    <div class="form-group">
                        <label>解除原因 (可选)</label>
                        <textarea id="unbind-reason" class="form-control" placeholder="请输入解除原因，医生将收到您的反馈"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary cancel-unbind">取消</button>
                    <button class="btn btn-danger confirm-unbind" data-relationship-id="${relationshipId}">确认解除</button>
                </div>
            </div>
        `;
        
        // 添加到页面
        document.body.appendChild(modal);
        
        // 防止滚动
        document.body.style.overflow = 'hidden';
        
        // 显示模态框
        setTimeout(() => {
            modal.classList.add('show');
        }, 10);
        
        // 关闭按钮
        modal.querySelector('.close-modal').addEventListener('click', () => {
            closeModal(modal);
        });
        
        // 取消按钮
        modal.querySelector('.cancel-unbind').addEventListener('click', () => {
            closeModal(modal);
        });
        
        // 点击模态框外部关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                closeModal(modal);
            }
        });
        
        // 确认解除按钮
        modal.querySelector('.confirm-unbind').addEventListener('click', function() {
            const reason = modal.querySelector('#unbind-reason').value.trim();
            unbindDoctor(relationshipId, reason);
            closeModal(modal);
        });
    }
    
    // 解除医生绑定
    function unbindDoctor(relationshipId, reason) {
        // TODO: 实现解除医生绑定的API调用
        // 由于后端API尚未提供，此处仅显示通知，实际项目中需要调用对应的API
        showNotification('解除绑定功能尚未实现', 'info');
        
        // 示例API调用，实际项目中应替换为正确的API
        /*
        fetch(`/api/patient/unbind-doctor/${relationshipId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ reason: reason }),
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('解除绑定失败');
            }
            return response.json();
        })
        .then(data => {
            // 显示成功通知
            showNotification('已成功解除医生绑定', 'success');
            
            // 重新加载当前医生信息
            loadPatientCurrentDoctor();
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('解除绑定失败，请重试', 'error');
        });
        */
    }
    
    // 加载医生专业资料
    function loadDoctorProfile() {
        // 从会话存储中获取当前用户信息
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        if (!userData.id || userData.role !== 'DOCTOR') {
            return;
        }
        
        // 获取表单元素
        const specialtyInput = document.getElementById('doctor-specialty');
        const hospitalInput = document.getElementById('doctor-hospital');
        const titleInput = document.getElementById('doctor-title');
        const licenseInput = document.getElementById('doctor-license');
        const bioProfessionalInput = document.getElementById('doctor-professional-bio');
        
        if (!specialtyInput) return;
        
        // 显示加载状态
        const saveButton = document.getElementById('save-doctor-profile-btn');
        if (saveButton) {
            saveButton.disabled = true;
            saveButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 加载中...';
        }
        
        // 获取医生信息
        fetch(`/api/doctors/${userData.id}`, {
            method: 'GET',
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('获取医生信息失败');
            }
            return response.json();
        })
        .then(doctor => {
            // 填充表单
            if (specialtyInput) specialtyInput.value = doctor.specialty || '';
            if (hospitalInput) hospitalInput.value = doctor.hospital || '';
            if (titleInput) titleInput.value = doctor.title || '';
            if (licenseInput) licenseInput.value = doctor.licenseNumber || '';
            if (bioProfessionalInput) bioProfessionalInput.value = doctor.professionalBio || '';
            
            // 恢复按钮状态
            if (saveButton) {
                saveButton.disabled = false;
                saveButton.textContent = '保存更改';
            }
            
            // 添加保存按钮事件
            if (saveButton) {
                saveButton.addEventListener('click', saveDoctorProfile);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('加载医生资料失败，请稍后重试', 'error');
            
            // 恢复按钮状态
            if (saveButton) {
                saveButton.disabled = false;
                saveButton.textContent = '保存更改';
            }
        });
    }
    
    // 保存医生专业资料
    function saveDoctorProfile() {
        // 从会话存储中获取当前用户信息
        const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
        if (!userData.id || userData.role !== 'DOCTOR') {
            showNotification('无法获取用户信息，请重新登录', 'error');
            return;
        }
        
        // 获取表单元素
        const specialtyInput = document.getElementById('doctor-specialty');
        const hospitalInput = document.getElementById('doctor-hospital');
        const titleInput = document.getElementById('doctor-title');
        const licenseInput = document.getElementById('doctor-license');
        const bioProfessionalInput = document.getElementById('doctor-professional-bio');
        
        // 获取表单数据
        const specialty = specialtyInput ? specialtyInput.value.trim() : '';
        const hospital = hospitalInput ? hospitalInput.value.trim() : '';
        const title = titleInput ? titleInput.value.trim() : '';
        const licenseNumber = licenseInput ? licenseInput.value.trim() : '';
        const professionalBio = bioProfessionalInput ? bioProfessionalInput.value.trim() : '';
        
        // 验证必填字段
        if (!specialty) {
            showNotification('请填写专业领域', 'error');
            specialtyInput.focus();
            return;
        }
        
        // 构建更新数据
        const doctorUpdateData = {
            specialty: specialty,
            hospital: hospital,
            title: title,
            licenseNumber: licenseNumber,
            professionalBio: professionalBio
        };
        
        // 显示保存中状态
        const saveButton = document.getElementById('save-doctor-profile-btn');
        if (saveButton) {
            saveButton.disabled = true;
            saveButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
        }
        
        // 发送更新请求
        fetch(`/api/doctors/${userData.id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(doctorUpdateData),
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('更新医生资料失败');
            }
            return response.json();
        })
        .then(updatedDoctor => {
            // 显示成功通知
            showNotification('医生资料保存成功', 'success');
            
            // 恢复按钮状态
            if (saveButton) {
                saveButton.disabled = false;
                saveButton.textContent = '保存更改';
            }
            
            // 更新会话存储中的用户数据
            userData.specialty = updatedDoctor.specialty;
            userData.hospital = updatedDoctor.hospital;
            userData.title = updatedDoctor.title;
            sessionStorage.setItem('user', JSON.stringify(userData));
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('保存医生资料失败，请重试', 'error');
            
            // 恢复按钮状态
            if (saveButton) {
                saveButton.disabled = false;
                saveButton.textContent = '保存更改';
            }
        });
    }
    
    // 患者管理按钮点击事件
    if (document.getElementById('go-to-patients-btn')) {
        document.getElementById('go-to-patients-btn').addEventListener('click', function() {
            // 切换到患者管理页面
            const patientsMgmtNav = document.querySelector('.nav-item[data-page="patients"]');
            if (patientsMgmtNav) {
                patientsMgmtNav.click();
            }
        });
    }
    
    // Add event listener for the refresh doctor info button
    const refreshDoctorInfoBtn = document.getElementById('refresh-doctor-info');
    if (refreshDoctorInfoBtn) {
        refreshDoctorInfoBtn.addEventListener('click', function() {
            loadPatientCurrentDoctor();
        });
    }
}); 